package collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2024/09/02
 * map的使用方式
 */
public class MapTest {
    public static void main(String[] args) {
//        Map<String, User> map = new HashMap<>();
//
//        map.put("010101", new User("张三", 12));
//        map.put("010102", new User("张4", 13));
//        map.put("010106", new User("张5", 14));
//        map.put("010103", new User("张6", 15));
//        map.put("010105", new User("张7", 16));
//        System.out.println(map.get("010101"));

        HashMap<Integer, String> hashMap = new HashMap<>(16);
        for (int i = 0; i < 100; i++) {
            hashMap.put(i, "d");
        }

        //HashMap遍历，第一种方式
        Set<Integer> integers = hashMap.keySet();
        //HashMap中是没有直接iterator的，所以要拿到key
        Iterator<Integer> iterator = integers.iterator();
        while (iterator.hasNext()) {
            Integer key = iterator.next();
            System.out.println("key = " + key);
            System.out.println("value = " + hashMap.get(key));
        }

        //第二种
        Set<Map.Entry<Integer, String>> entries = hashMap.entrySet();
        Iterator<Map.Entry<Integer, String>> iterator1 = entries.iterator();
        while (iterator1.hasNext()) {
            //错误的写法，原因：看笔记
//            System.out.println(iterator1.next().getKey());
//            System.out.println(iterator1.next().getValue());

            //正确的
            Map.Entry<Integer, String> next = iterator1.next();
            System.out.println("Key= " + next.getKey());
            System.out.println("Value= " + next.getValue());


            //第三种，增强for循环
            for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
                System.out.println(entry.getKey());
                System.out.println(entry.getValue());
            }
        }
    }
}
